#!coding:utf8
"""
Created on June 20, 2013

@author: join
"""
import shlex
import subprocess

from rsa.key import PublicKey,PrivateKey
import rsa,cPickle
from datetime import datetime,timedelta


def gen_license():
    pubkey = '''-----BEGIN RSA PUBLIC KEY-----
    MIIBCgKCAQEAyZsPJ4kpFrPXFbnr2JOOgXRcmbVcHnbXTdjhN0iwaHVn0v9UeBL1
    tWLmRZQDB6jlUJ2G2ENONjjHLR+qJUdPAGSEOIYo0r2mkYun9tY/7VSes/llUR+I
    AzVFMmnE2QQ0cQVBTwKk08aCzWOFFOzz940rohAbPB3vczpq783CcYxFCzFvdX7e
    rf+Voor7QvTQZ34gl4x7nXJUgAQefpOZU5bPzfO732Iy5Nh9E4bY612PTQpN+1/i
    Lc//nWOzYRBZwf6zEPELYIN2skHqQmhH7PNI6OTyRRPlBf5/sTr2FPQx4Xh1OsHD
    hbSDWY+LHN8klHInNvZ51/6sc9xYkKO/qwIDAQAB
    -----END RSA PUBLIC KEY-----
    '''
    while 1:
        hid = raw_input("硬件id:")
        if hid: break

    # while 1:
    # 	cpu = raw_input("CPU(个):")
    # 	try:
    # 		cpu = int(cpu)
    # 		break
    # 	except:
    # 		print "请输入数字"
    # 		continue

    # while 1:
    # 	mem = raw_input("内存(GB):")
    # 	try:
    # 		mem = int(mem)
    # 		break
    # 	except:
    # 		print "请输入数字"
    # 		continue

    while 1:
        inst = raw_input("实例(个):")
        try:
            inst = int(inst)
            break
        except:
            print "请输入数字"
            continue

    while 1:
        etime = raw_input("时间(天):")
        try:
            etime = int(etime)
            break
        except:
            print "请输入数字"
            continue

    while 1:
        version = raw_input("版本(1-桌面版,2-标准版,3-企业版):")
        try:
            version = int(version)
            if version not in [1,2,3]:
                raise Exception()
            break
        except:
            print "请输入数字(1-桌面版,2-标准版,3-企业版)"
            continue


    license = {
        #'cpu':cpu,
        'hardwareid':hid,
        #'mem':mem,
        'inst':inst,
        'time':datetime.now().date() + timedelta(etime) if etime != -1 else -1,#天
        'version':version
    }


    msg = cPickle.dumps(license)

    emsg = rsa.encrypt(msg, PublicKey.load_pkcs1(pubkey))

    emsg = rsa.transform.binascii.b2a_hex(emsg)

    print emsg
    # f = file("/etc/licenseinfo", "w")
    # f.write(emsg)
    # f.close()

    dmsg = rsa.transform.binascii.a2b_hex(emsg)

    dmsg = rsa.decrypt(dmsg,PrivateKey.load_pkcs1('''-----BEGIN RSA PRIVATE KEY-----
    MIIEqQIBAAKCAQEAyZsPJ4kpFrPXFbnr2JOOgXRcmbVcHnbXTdjhN0iwaHVn0v9U
    eBL1tWLmRZQDB6jlUJ2G2ENONjjHLR+qJUdPAGSEOIYo0r2mkYun9tY/7VSes/ll
    UR+IAzVFMmnE2QQ0cQVBTwKk08aCzWOFFOzz940rohAbPB3vczpq783CcYxFCzFv
    dX7erf+Voor7QvTQZ34gl4x7nXJUgAQefpOZU5bPzfO732Iy5Nh9E4bY612PTQpN
    +1/iLc//nWOzYRBZwf6zEPELYIN2skHqQmhH7PNI6OTyRRPlBf5/sTr2FPQx4Xh1
    OsHDhbSDWY+LHN8klHInNvZ51/6sc9xYkKO/qwIDAQABAoIBAD9ZMtTYe4m/rtkL
    17jw/Llex+4gl7aW3yZ9/J6zf4MDSUF6q58jTgPV9MduL9mLT6saJJH17DCLfMKI
    DZ2zH3bfHtDoDxHRN/LJ8FhWkDXR/iBNQHHSN5nSdlDV/V23vYa6AQCDsyk8WkOR
    fvLJVgu2VzyQVQ551U7RXiux5XLGG8Go9KaxpRH3IAU97JBwgkHRthwiLW7zNjqO
    AQ94xlm9hlhfM5+qeBXUDjxbNdet3+FSpZF5UrgUnojQ6xGpmYgTWnlpyW0We24Y
    nQnZ3Oy18n2t02V/U/MJ7NcfdTBWxhWHmMS4B8LzNUYUumcvOlPMAI6ZLyXG/In9
    dH0SlEECgYkA0jVLzsXNOcYRtHNH21rYtrVg3goUDHCjesgqHoiDAaUECGgUuSjm
    ovCGYkOz5gBI5X104KDoQQK2gvi1cmIyPLPmkyN/YUetkAvROfR41DU4e0MNl1U2
    /muSFnAyEL4IJ1lMJVoLPe77kDH+hIeVQ0sl6gBvh44JZGOfSExG/WTneXhR8QEd
    ywJ5APWGBvM5jdiWqYHJ/rySDELNJQy1dJb+Sp01938zXIWVNin25s/717h5JuzA
    IK4sb/fT51AatNn5iPH3xY31s9ng7B7iNPcC4IvgTER6jBeWmlLoLJaPq6XLvT75
    7xDwkzQksfrhzZxfPKh6JpwBULKHZKeMHi+poQKBiD1kG1O0KQ+qbRlKYb4KdihG
    KJgwUVKgwt3k/4gTTk94pgjefM7mxxTnMhgYtb2Cb8e2MCA6Xho+dJcjk7poO0vH
    LpviTh1XFbVv/hby8ybmtCwrlRiRZpI/UFcFRVnmZfM3/SkbdxULaqTeNPr3rfwN
    QnFo1ym7rbqH7cjrnf/7LC8pmKTOMqkCeHq+sqLOVze8uqmETrH/YdnTrX4ZCVyj
    bLID1OPmzY6K9jUsll/MTCCRkQAzXSM2XBPOAIpvj5KZyfkOIdnCyFNYuzMFa+1B
    pvjG/doOWhNA244vPHtZADs3DDl7wiT54N3kqoX+dUiD5FNmHf9IOQvH3G5XApBZ
    gQKBiQCXSSS9FGrGSW7bkTsgr9LFUKq5/wi50MHY5j2bxhH+PHGCQ8YHtPCBgpdm
    udM9Ga6jkA8jbW39v9NMRhpMqtXimW3RK/HCWAW54DOvaTRXuhon7lGiRStWRO9K
    8v6rEaI8Ac+q2l+CFnSwj87jhHyZg7jq0z4TmHf87Vkd6T0oqeRUnDE/lRs5
    -----END RSA PRIVATE KEY-----'''))


    print cPickle.loads(dmsg)

def execute(*cmd, **kwargs):
    """
    Helper method to execute command with optional retry.

    :cmd                Passed to subprocess.Popen.
    :process_input      Send to opened process.
    :check_exit_code    Defaults to 0. Raise exception.ProcessExecutionError
                        unless program exits with this code.
    :delay_on_retry     True | False. Defaults to True. If set to True, wait a
                        short amount of time before retrying.
    :attempts           How many times to retry cmd.
    :run_as_root        True | False. Defaults to False. If set to True,
                        the command is prefixed by the command specified
                        in the root_helper FLAG.

    :raises exception.Error on receiving unknown arguments
    :raises exception.ProcessExecutionError
    """

    process_input = kwargs.pop('process_input', None)
    check_exit_code = kwargs.pop('check_exit_code', 0)
    attempts = kwargs.pop('attempts', 1)
    run_as_root = kwargs.pop('run_as_root', False)
    is_debug = kwargs.pop('is_debug', True)
    if len(kwargs):
        print 'Got unknown keyword args to utils.execute: %r'
        return

    if run_as_root:
        cmd = shlex.split('sudo') + list(cmd)
    cmd = map(str, cmd)

    while attempts > 0:
        attempts -= 1
        try:
            _PIPE = subprocess.PIPE
            obj = subprocess.Popen(cmd,
                                   stdin=_PIPE,
                                   stdout=_PIPE,
                                   stderr=_PIPE,
                                   close_fds=True)
            result = None
            if process_input is not None:
                result = obj.communicate(process_input)
            else:
                result = obj.communicate()
            obj.stdin.close()
            _returncode = obj.returncode
            if _returncode:
                print 'result is %s'%_returncode
            return result
        except Exception as e:
            print 'exception was %s ' % e


if __name__ == '__main__':
    gen_license()